import { Html, Line } from '@react-three/drei';
import { round } from 'lodash-es';
import {
  ChangeEvent,
  KeyboardEvent,
  useEffect,
  useMemo,
  useState,
} from 'react';
import { Line3, Vector3 } from 'three';

interface Props {
  line: Line3;
  onChange: (value: { line: Line3; size: number; delta: number }) => void;
}

export function PositionLine(props: Props) {
  const { line } = props;
  const middle = line.getCenter(new Vector3());
  const getOriginSize = () => round(line.distance(), 2);
  const originSize = useMemo(getOriginSize, [line]);
  const [size, setSize] = useState<string>();
  useEffect(() => {
    setSize(String(originSize));
  }, [originSize]);
  function onChange(e: ChangeEvent<HTMLInputElement>) {
    const newSize = e.target.value;
    setSize(String(newSize));
  }
  function onBlur(e: ChangeEvent<HTMLInputElement>) {
    const newSize = Number(e.target.value);
    emitChange(newSize);
  }
  function emitChange(value: number) {
    const newSize = value;
    const delta = newSize - originSize;
    props.onChange({ line, size: newSize, delta });
  }
  function onEnter(e: KeyboardEvent<HTMLInputElement>) {
    const el = e.target as HTMLInputElement;
    const value = Number(el.value);
    if (e.key === 'Enter') {
      emitChange(value);
    }
  }

  return (
    <Line points={[line.start, line.end]} color={'#645F5C'}>
      <Html center position={middle} zIndexRange={[0, 1000]}>
        <input
          className="bg-white bg-opacity-50"
          type="text"
          title={size}
          value={size}
          style={{ width: 40 }}
          onChange={onChange}
          onBlur={onBlur}
          onKeyDown={onEnter}
        />
      </Html>
    </Line>
  );
}
